"""
配置管理模块
"""

import yaml
import os
from pathlib import Path
from typing import Dict, Any, Optional
import logging

class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_path: str = "config.yaml"):
        """初始化配置管理器"""
        self.config_path = Path(config_path)
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            if self.config_path.exists():
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    config = yaml.safe_load(f)
            else:
                # 默认配置
                config = self._get_default_config()
                self._save_config(config)
            
            return config
        except Exception as e:
            logging.error(f"加载配置文件失败: {e}")
            return self._get_default_config()
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            'processing': {
                'batch_size': 4,
                'overlap_ratio': 0.25,
                'confidence_threshold': 0.85,
                'max_retries': 3,
                'timeout': 120
            },
            'output': {
                'naming_convention': 'intelligent',
                'format': 'PNG',
                'quality': 95,
                'save_bbox_visualization': True
            },
            'target_sizes': {
                'square': [1024, 1024],
                'portrait': [768, 1024],
                'small': [512, 512]
            },
            'ollama': {
                'model': 'qwen2.5vl:7b',
                'base_url': 'http://localhost:6399',
                'timeout': 120,
                'available_models': [
                    'qwen2.5vl:7b',
                    'llava:7b',
                    'llava:13b',
                    'bakllava:7b',
                    'moondream:1.8b',
                    'cogvlm:7b'
                ],
                'auto_detect': True
            },
            'threading': {
                'max_workers': 8,
                'io_pool_size': 4,
                'compute_pool_size': 4
            },
            'cache': {
                'max_size': 100,
                'ttl': 3600
            },
            'logging': {
                'level': 'INFO',
                'file': 'logs/processing.log',
                'max_size': '10MB',
                'backup_count': 5
            }
        }
    
    def _save_config(self, config: Dict[str, Any]) -> None:
        """保存配置文件"""
        try:
            self.config_path.parent.mkdir(parents=True, exist_ok=True)
            with open(self.config_path, 'w', encoding='utf-8') as f:
                yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
        except Exception as e:
            logging.error(f"保存配置文件失败: {e}")
    
    def get_config(self) -> Dict[str, Any]:
        """获取配置"""
        return self.config
    
    def update_config(self, updates: Dict[str, Any]) -> None:
        """更新配置"""
        self._deep_update(self.config, updates)
        self._save_config(self.config)
    
    def _deep_update(self, base_dict: Dict, update_dict: Dict) -> None:
        """深度更新字典"""
        for key, value in update_dict.items():
            if key in base_dict and isinstance(base_dict[key], dict) and isinstance(value, dict):
                self._deep_update(base_dict[key], value)
            else:
                base_dict[key] = value
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        keys = key.split('.')
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value